const db = require('../model/index');
const User = db.models.User;
const Department = db.models.Department;
const BrowsePrivileges = db.models.BrowsePrivileges;
const ApprovalPrivileges = db.models.ApprovalPrivileges;

// todo: 用ES7的修饰器来写更好，可惜用babel太麻烦了
/**
 * browseKey为空则只是验证用户存在
 */
const auth = function(browseKey) {
  return async function(ctx, next) {
    let token = ctx.request.headers['token'];
    let user = await User.findOne({
      where: {
        salt: token,
      },
      include: [{
        model: Department,
        as: 'Department',
        include: [{
          model: BrowsePrivileges,
        }]
      }, {
        model: ApprovalPrivileges,
        as: 'ApprovalPrivileges'
      }]
    });
    if(!user) {  // 如果不存在此用户
      ctx.body = {
        code: 100,
        msg: {
          error: '用户不存在',
        }
      };
      return;
    }
    // todo: 无法赋值，除非用.update更改或者将user变为非instance
    // user.dataValues.BrowsePrivileges = user.Department.BrowsePrivilege;  // 赋值以向下兼容
    // console.log(user.BrowsePrivileges, user.Department.BrowsePrivilege);
    if (browseKey && user.Department.BrowsePrivilege[browseKey] === false) {  // 如果用户无操作权限
      ctx.body = {
        code: 100,
        msg: {
          error: '越权操作',
        }
      };
      return;
    }

    ctx.user = user;
    await next();
  }
};

module.exports = auth;
